package com.hou.zookeeper.curator;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class DoubleBarrier {
    /**
     * zookeeper地址
     */
    static final String CONNECT_ADDR = "192.168.171.128:2181,192.168.171.129:2181,192.168.171.130:2181";
    /**
     * session超时时间
     */
    static final int SESSION_OUTTIME = 5000;//ms
    static DistributedBarrier barrier;

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                try {
                    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 10);
                    CuratorFramework cf = CuratorFrameworkFactory.builder()
                            .connectString(CONNECT_ADDR)
                            .sessionTimeoutMs(SESSION_OUTTIME)
                            .retryPolicy(retryPolicy)
                            .build();
                    cf.start();
                    barrier = new DistributedBarrier(cf, "/test");
                    System.out.println(Thread.currentThread().getName() + "设置barrier!");
                    barrier.setBarrier();//设置
                    barrier.waitOnBarrier();    //等待Barrier释放,准备一起执行
                    System.out.println("---------开始执行程序----------");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, "t" + i).start();
        }
        Thread.sleep(10000);
        if (barrier != null) {
            System.out.println("启动所有线程");
            barrier.removeBarrier();//删除屏障
        }
    }
}
